package com.lsh.oms.core.service.sms;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.oms.core.constant.ShortMessageConstants;
import com.lsh.oms.core.exception.ExBase;
import com.lsh.oms.core.model.sms.ShortMessageModel;
import com.lsh.oms.core.service.asynservice.IEventListener;
import com.lsh.oms.core.utils.http.HttpClientTemplate;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-groupon
 *
 * @author peter
 * 北京链商电子商务有限公司
 * Desc: 类功能描述
 * Package Name: com.lsh.groupon.core.ShortMessageService
 * Time: 2017-07-04 上午11:01
 */
@Service
public class ShortMessageService implements IEventListener {

    private static final Logger logger = Logger.getLogger(ShortMessageService.class);

    @Value("${short.message.url}")
    private String url;

    @Value("${short.message.newurl}")
    private String newUrl;

    @Value("${short.message.appid}")
    private String appId;

    @Value("${short.message.sign}")
    private String sign;

    @Subscribe
    public void asyncSendMessage(ShortMessageModel shortMessage) {
        for (String phone : shortMessage.getPhones()) {
            try {
                this.sendMessage(phone, shortMessage.getContent());
            } catch (Exception e) {
                logger.error("[turn arrival status] error:" + e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
    }

    @Subscribe
    @AllowConcurrentEvents
    public boolean asyncSendMessage(ShortMessage shortMessage) throws BusinessException {
        boolean isSuccess = false;
        try {

            if (StringUtils.isBlank(shortMessage.getProject())) {
                isSuccess = this.sendMessage(shortMessage.getTo(), shortMessage.getContent());
            } else {
                isSuccess = this.sendMessage(shortMessage.getTo(), shortMessage.getProject(), shortMessage.getContent());
            }

            if (!isSuccess) {
                throw ExBase.ERROR_SEND_MESSAGE.exception();
            }
        } catch (Exception e) {
            logger.error("[turn arrival status] error:" + e.getMessage());
            logger.error(e.getMessage(), e);
        }

        return isSuccess;
    }


    public boolean sendMessage(String mobiles, String content) throws BusinessException {
        Map<String, Object> params = new HashMap<>(7);

        content.replaceAll(" ", "");
        params.put(ShortMessageConstants.MOBILES, mobiles);
        params.put(ShortMessageConstants.CONTENT, content);
        params.put(ShortMessageConstants.NAME, ShortMessageConstants.NAME_VALUE);
        params.put(ShortMessageConstants.PASS, ShortMessageConstants.PASS_VALUE);

        logger.info("[send message] url:" + newUrl + ", params:" + JSON.toJSONString(params));
        String result = HttpClientTemplate.doGet(newUrl, params);
        logger.info("[send message] result:" + result);
        if (StringUtils.isBlank(result)) {
            throw ExBase.ERROR_SEND_MESSAGE.exception();
        }

        return true;
    }

    public boolean sendMessage(String to, String project, String content) throws BusinessException {
        Map<String, Object> params = new HashMap<>(8);
        params.put(ShortMessageConstants.APP_ID, appId);
        params.put(ShortMessageConstants.TO, to);
        params.put(ShortMessageConstants.PROJECT, project);
        params.put(ShortMessageConstants.SIGN, sign);
        params.put(ShortMessageConstants.VARS, content);

        logger.info("[send message] url:" + url + ", params:" + JSON.toJSONString(params));
        String result = HttpClientTemplate.doPost(url, params);
        logger.info("[send message] result:" + result);
        if (StringUtils.isBlank(result)) {
            throw ExBase.ERROR_SEND_MESSAGE.exception();
        }

        JSONObject res;
        try {
            res = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[send message] error:" + e.getMessage());
            logger.error(e.getMessage(), e);
            throw ExBase.ERROR_SEND_MESSAGE.exception();
        }

        if (StringUtils.isBlank(res.getString(ShortMessageConstants.RESULT_STATUS))) {
            throw ExBase.ERROR_SEND_MESSAGE.exception();
        }

        if (res.getString(ShortMessageConstants.RESULT_STATUS).equals(ShortMessageConstants.RESULT_SUCCESS_STATUS)) {
            return true;
        } else {
            return false;
        }
    }

    public static String buildPoMessage(String msg, String error) {
        JSONObject message = new JSONObject();
        message.put("msg", msg);
        message.put("error", error);
        return message.toJSONString();
    }

    public static String buildOrderMessage(String orderCode) {
        JSONObject message = new JSONObject();
        message.put("order_code", orderCode);
        return message.toJSONString();
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Getter
    @Setter
    public class ShortMessage {

        private String to;
        private String project;
        private String content;

        public ShortMessage(String to, String content) {

            this.to = to;
            this.content = content;
        }
    }

}
